<!-- 文章列表管理页面 - 提供文章的搜索、筛选、批量操作等功能 -->
<template>
    <div class="post-list">
        <!-- 示例数据提示 -->
        <el-alert v-if="isUsingSampleData" title="示例数据模式" type="warning" :closable="false" class="sample-data-notice">
            <template #default>
                当前显示的是示例数据，实际数据获取失败。请检查网络连接或后端服务状态。
            </template>
        </el-alert>

        <!-- 搜索和筛选区域 -->
        <div class="search-filter-section">
            <!-- 搜索框 -->
            <div class="search-box">
                <el-input v-model="searchKeyword" placeholder="搜索文章标题..." clearable @input="handleSearch">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>

            <!-- 筛选条件 -->
            <div class="filter-box">
                <!-- 分类筛选 -->
                <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="handleFilter">
                    <el-option v-for="category in categories" :key="category.id" :label="category.name"
                        :value="category.id" />
                </el-select>

                <!-- 状态筛选 -->
                <el-select v-model="selectedStatus" placeholder="选择状态" clearable @change="handleFilter">
                    <el-option label="草稿" value="draft" />
                    <el-option label="已发布" value="published" />
                    <el-option label="已归档" value="archived" />
                </el-select>
            </div>

            <!-- 操作按钮 -->
            <div class="action-box">
                <el-button type="primary" @click="createPost">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新建文章
                </el-button>
            </div>
        </div>

        <!-- 文章列表表格 -->
        <div class="table-section">
            <!-- 加载骨架屏 -->
            <div v-if="loading" class="table-skeleton">
                <div class="skeleton-header">
                    <div class="skeleton-row">
                        <div class="skeleton-checkbox"></div>
                        <div class="skeleton-title"></div>
                        <div class="skeleton-category"></div>
                        <div class="skeleton-status"></div>
                        <div class="skeleton-time"></div>
                        <div class="skeleton-views"></div>
                        <div class="skeleton-actions"></div>
                    </div>
                </div>
                <div class="skeleton-body">
                    <div v-for="i in 5" :key="i" class="skeleton-row">
                        <div class="skeleton-checkbox"></div>
                        <div class="skeleton-content">
                            <div class="skeleton-title"></div>
                            <div class="skeleton-tags">
                                <div class="skeleton-tag"></div>
                                <div class="skeleton-tag"></div>
                            </div>
                        </div>
                        <div class="skeleton-category"></div>
                        <div class="skeleton-status"></div>
                        <div class="skeleton-time"></div>
                        <div class="skeleton-views"></div>
                        <div class="skeleton-actions">
                            <div class="skeleton-btn"></div>
                            <div class="skeleton-btn"></div>
                            <div class="skeleton-btn"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 使用Element Plus表格组件，支持多选 -->
            <el-table v-else :data="filteredPosts" style="width: 100%" @selection-change="handleSelectionChange">
                <!-- 空状态 -->
                <template #empty>
                    <div class="empty-state">
                        <el-empty description="暂无数据" />
                    </div>
                </template>
                <!-- 多选列 -->
                <el-table-column type="selection" width="55" />

                <!-- 文章标题列 -->
                <el-table-column prop="title" label="标题" min-width="200">
                    <template #default="{ row }">
                        <div class="post-title">
                            <span class="title-text">{{ row.title }}</span>
                            <!-- 文章标签 -->
                            <div class="post-tags">
                                <el-tag v-for="tag in row.tags" :key="tag" size="small" class="tag-item">
                                    {{ tag }}
                                </el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <!-- 分类列 -->
                <el-table-column prop="categoryName" label="分类" width="120">
                    <template #default="{ row }">
                        <el-tag size="small" type="info">{{ row.categoryName }}</el-tag>
                    </template>
                </el-table-column>

                <!-- 状态列 -->
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)" size="small">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>

                <!-- 创建时间列 -->
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="{ row }">
                        {{ formatDate(row.createTime) }}
                    </template>
                </el-table-column>

                <!-- 浏览量列 -->
                <el-table-column prop="viewCount" label="浏览量" width="100">
                    <template #default="{ row }">
                        <span class="view-count">{{ row.viewCount }}</span>
                    </template>
                </el-table-column>

                <!-- 操作列 - 固定在右侧 -->
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="{ row }">
                        <div class="action-buttons">
                            <!-- 编辑按钮 -->
                            <el-button size="small" type="primary" plain class="action-btn" @click="editPost(row.id)">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>
                            <!-- 查看按钮 -->
                            <el-button size="small" type="success" plain class="action-btn" @click="viewPost(row.id)">
                                <el-icon>
                                    <View />
                                </el-icon>
                                查看
                            </el-button>
                            <!-- 更多操作下拉菜单 -->
                            <el-dropdown @command="handleCommand" trigger="click">
                                <el-button size="small" type="info" plain class="action-btn more-btn">
                                    <el-icon>
                                        <MoreFilled />
                                    </el-icon>
                                    更多
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <!-- 置顶/取消置顶选项 -->
                                        <el-dropdown-item :command="{ action: 'toggleTop', id: row.id }">
                                            <el-icon>
                                                <ArrowUp />
                                            </el-icon>
                                            {{ row.isTop ? '取消置顶' : '置顶' }}
                                        </el-dropdown-item>
                                        <!-- 推荐/取消推荐选项 -->
                                        <el-dropdown-item :command="{ action: 'toggleRecommend', id: row.id }">
                                            <el-icon>
                                                <View />
                                            </el-icon>
                                            {{ row.isRecommend ? '取消推荐' : '推荐' }}
                                        </el-dropdown-item>
                                        <!-- 删除选项 -->
                                        <el-dropdown-item divided :command="{ action: 'delete', id: row.id }">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                            删除
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-section">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 批量操作区域 -->
        <div class="batch-actions" v-if="selectedPosts.length > 0">
            <el-button size="small" @click="batchDelete">批量删除</el-button>
            <el-button size="small" type="primary" @click="batchPublish">批量发布</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
// 导入Vue 3 Composition API核心功能
import { ref, computed, onMounted } from 'vue'
// 导入Vue Router用于页面导航
import { useRouter } from 'vue-router'
// 导入Element Plus组件和消息提示
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入Element Plus图标组件
import { Search, Plus, ArrowDown, Edit, View, MoreFilled, ArrowUp, Delete, Loading } from '@element-plus/icons-vue'
// 导入API工具函数
import { get, post, del, API_PATHS } from '@/utils/api'

// 获取路由实例，用于页面跳转
const router = useRouter()

// 响应式数据定义
const loading = ref(false) // 页面加载状态
const searchKeyword = ref('') // 搜索关键词
const selectedCategory = ref('') // 选中的分类
const selectedStatus = ref('') // 选中的状态
const currentPage = ref(1) // 当前页码
const pageSize = ref(20) // 每页显示数量
const total = ref(0) // 总数据量
const selectedPosts = ref<any[]>([]) // 选中的文章列表
const isUsingSampleData = ref(false) // 是否使用示例数据

// TypeScript 接口定义
interface Post {
    id: number
    title: string
    categoryName: string
    tags: string[]
    status: 'draft' | 'published' | 'archived'
    createTime: string
    viewCount: number
    isTop: boolean
    isRecommend: boolean
}

interface Category {
    id: number
    name: string
    description?: string
}

interface PostListResponse {
    posts: Post[]
    total: number
    page: number
    pageSize: number
}

interface PostSearchRequest {
    keyword?: string
    categoryId?: number
    status?: string
    page: number
    pageSize: number
}

// 示例数据
const samplePosts: Post[] = [
    {
        id: 1,
        title: 'Vue 3 组合式 API 详解',
        categoryName: '前端开发',
        tags: ['Vue', 'JavaScript'],
        status: 'published',
        createTime: '2024-12-19T10:30:00Z',
        viewCount: 1250,
        isTop: true,
        isRecommend: true
    },
    {
        id: 2,
        title: 'TypeScript 高级类型指南',
        categoryName: '编程语言',
        tags: ['TypeScript', 'JavaScript'],
        status: 'published',
        createTime: '2024-12-18T14:20:00Z',
        viewCount: 890,
        isTop: false,
        isRecommend: true
    },
    {
        id: 3,
        title: 'CSS Grid 布局完全指南',
        categoryName: '前端开发',
        tags: ['CSS', '布局'],
        status: 'draft',
        createTime: '2024-12-17T09:15:00Z',
        viewCount: 0,
        isTop: false,
        isRecommend: false
    }
]

const sampleCategories: Category[] = [
    { id: 1, name: '前端开发', description: '前端技术相关文章' },
    { id: 2, name: '编程语言', description: '各种编程语言教程' },
    { id: 3, name: '后端开发', description: '后端技术相关文章' },
    { id: 4, name: '数据库', description: '数据库相关技术' },
    { id: 5, name: '运维部署', description: '服务器运维和部署' }
]

// 使用示例数据的函数
const useSampleData = () => {
    posts.value = samplePosts
    categories.value = sampleCategories
    total.value = samplePosts.length
    isUsingSampleData.value = true
}

// 响应式数据
const posts = ref<Post[]>([])
const categories = ref<Category[]>([])

// 计算属性 - 根据搜索和筛选条件过滤文章列表
const filteredPosts = computed(() => {
    let result = posts.value

    // 根据搜索关键词过滤
    if (searchKeyword.value) {
        result = result.filter(post =>
            post.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
    }

    // 根据选中分类过滤
    if (selectedCategory.value) {
        result = result.filter(post =>
            post.categoryName === categories.value.find(c => c.id === Number(selectedCategory.value))?.name
        )
    }

    // 根据选中状态过滤
    if (selectedStatus.value) {
        result = result.filter(post => post.status === selectedStatus.value)
    }

    return result
})

// API调用函数

/**
 * 获取文章列表
 */
const fetchPosts = async () => {
    loading.value = true
    try {
        const params: PostSearchRequest = {
            page: currentPage.value,
            pageSize: pageSize.value
        }

        if (searchKeyword.value) {
            params.keyword = searchKeyword.value
        }
        if (selectedCategory.value) {
            params.categoryId = Number(selectedCategory.value)
        }
        if (selectedStatus.value) {
            params.status = selectedStatus.value
        }

        // 构建查询参数
        const queryParams = new URLSearchParams()
        if (params.page) queryParams.append('page', params.page.toString())
        if (params.pageSize) queryParams.append('size', params.pageSize.toString())
        if (params.keyword) queryParams.append('keyword', params.keyword)
        if (params.categoryId) queryParams.append('categoryId', params.categoryId.toString())
        if (params.status) queryParams.append('status', params.status)

        const url = queryParams.toString() ? `${API_PATHS.ADMIN_ARTICLE.LIST}?${queryParams.toString()}` : API_PATHS.ADMIN_ARTICLE.LIST

        const response = await get<PostListResponse>(url, {
            timeout: 10000,
            retry: 3
        })

        if (response && response.success && response.data) {
            posts.value = response.data.posts
            total.value = response.data.total
            isUsingSampleData.value = false
            ElMessage.success('获取文章列表成功')
        } else {
            throw new Error('获取文章列表失败')
        }
    } catch (error) {
        console.error('获取文章列表失败:', error)
        useSampleData()
        ElMessage.warning('使用示例数据，实际数据获取失败')
    } finally {
        loading.value = false
    }
}

/**
 * 获取分类列表
 */
const fetchCategories = async () => {
    try {
        const response = await get<Category[]>(API_PATHS.ADMIN_ARTICLE.CATEGORIES, {
            timeout: 5000,
            retry: 2
        })

        if (response && response.success && response.data) {
            categories.value = response.data as unknown as Category[]
        } else {
            throw new Error('获取分类列表失败')
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
        categories.value = sampleCategories
    }
}

/**
 * 切换文章置顶状态
 */
const toggleTopAPI = async (id: number) => {
    try {
        const response = await post(API_PATHS.ADMIN_ARTICLE.TOGGLE_TOP(id.toString()), {}, {
            timeout: 5000,
            retry: 2
        })

        if (response && response.success) {
            ElMessage.success('置顶状态切换成功')
            await fetchPosts() // 重新获取数据
        } else {
            throw new Error('置顶状态切换失败')
        }
    } catch (error) {
        console.error('置顶状态切换失败:', error)
        ElMessage.error('置顶状态切换失败')
    }
}

/**
 * 切换文章推荐状态
 */
const toggleRecommendAPI = async (id: number) => {
    try {
        const response = await post(API_PATHS.ADMIN_ARTICLE.TOGGLE_RECOMMEND(id.toString()), {}, {
            timeout: 5000,
            retry: 2
        })

        if (response && response.success) {
            ElMessage.success('推荐状态切换成功')
            await fetchPosts() // 重新获取数据
        } else {
            throw new Error('推荐状态切换失败')
        }
    } catch (error) {
        console.error('推荐状态切换失败:', error)
        ElMessage.error('推荐状态切换失败')
    }
}

/**
 * 删除文章
 */
const deletePostAPI = async (id: number) => {
    try {
        const response = await del(API_PATHS.ADMIN_ARTICLE.DELETE(id.toString()), {
            timeout: 5000,
            retry: 2
        })

        if (response && response.success) {
            ElMessage.success('删除文章成功')
            await fetchPosts() // 重新获取数据
        } else {
            throw new Error('删除文章失败')
        }
    } catch (error) {
        console.error('删除文章失败:', error)
        ElMessage.error('删除文章失败')
    }
}

/**
 * 批量删除文章
 */
const batchDeleteAPI = async (ids: number[]) => {
    try {
        const response = await post(API_PATHS.ADMIN_ARTICLE.BATCH_DELETE, { ids }, {
            timeout: 10000,
            retry: 2
        })

        if (response && response.success) {
            ElMessage.success('批量删除成功')
            await fetchPosts() // 重新获取数据
        } else {
            throw new Error('批量删除失败')
        }
    } catch (error) {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败')
    }
}

/**
 * 批量发布文章
 */
const batchPublishAPI = async (ids: number[]) => {
    try {
        const response = await post(API_PATHS.ADMIN_ARTICLE.BATCH_PUBLISH, { ids }, {
            timeout: 10000,
            retry: 2
        })

        if (response && response.success) {
            ElMessage.success('批量发布成功')
            await fetchPosts() // 重新获取数据
        } else {
            throw new Error('批量发布失败')
        }
    } catch (error) {
        console.error('批量发布失败:', error)
        ElMessage.error('批量发布失败')
    }
}

// 方法定义

/**
 * 处理搜索输入
 * 重置页码并触发搜索
 */
const handleSearch = () => {
    currentPage.value = 1
    fetchPosts()
}

/**
 * 处理筛选条件变化
 * 重置页码并触发筛选
 */
const handleFilter = () => {
    currentPage.value = 1
    fetchPosts()
}

/**
 * 创建新文章
 * 跳转到文章编辑页面
 */
const createPost = () => {
    router.push('/admin/posts/edit')
}

/**
 * 编辑文章
 * 跳转到文章编辑页面
 * @param id - 文章ID
 */
const editPost = (id: number) => {
    router.push(`/admin/posts/edit/${id}`)
}

/**
 * 查看文章
 * 跳转到文章详情页面
 * @param id - 文章ID
 */
const viewPost = (id: number) => {
    router.push(`/blog-detail/${id}`)
}

/**
 * 处理表格选择变化
 * 更新选中的文章列表
 * @param selection - 选中的行数据
 */
const handleSelectionChange = (selection: any[]) => {
    selectedPosts.value = selection
}

/**
 * 处理下拉菜单命令
 * 根据命令类型执行相应的操作
 * @param command - 命令对象，包含action和id
 */
const handleCommand = async (command: any) => {
    switch (command.action) {
        case 'toggleTop':
            await toggleTop(command.id)
            break
        case 'toggleRecommend':
            await toggleRecommend(command.id)
            break
        case 'delete':
            await deletePost(command.id)
            break
    }
}

/**
 * 切换文章置顶状态
 * @param id - 文章ID
 */
const toggleTop = async (id: number) => {
    await toggleTopAPI(id)
}

/**
 * 切换文章推荐状态
 * @param id - 文章ID
 */
const toggleRecommend = async (id: number) => {
    await toggleRecommendAPI(id)
}

/**
 * 删除文章
 * 删除前会显示确认对话框
 * @param id - 要删除的文章ID
 */
const deletePost = async (id: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deletePostAPI(id)
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

/**
 * 批量删除文章
 * 删除前会显示确认对话框
 */
const batchDelete = async () => {
    try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedPosts.value.length} 篇文章吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const ids = selectedPosts.value.map(post => post.id)
        await batchDeleteAPI(ids)
        selectedPosts.value = []
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

/**
 * 批量发布文章
 * 将选中的草稿文章发布
 */
const batchPublish = async () => {
    try {
        const ids = selectedPosts.value.map(post => post.id)
        await batchPublishAPI(ids)
        selectedPosts.value = []
    } catch (error) {
        ElMessage.error('批量发布失败')
    }
}

/**
 * 处理分页大小变化
 * @param size - 新的分页大小
 */
const handleSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchPosts()
}

/**
 * 处理当前页变化
 * @param page - 新的页码
 */
const handleCurrentChange = (page: number) => {
    currentPage.value = page
    fetchPosts()
}

/**
 * 获取状态对应的标签类型
 * @param status - 文章状态
 * @returns 标签类型
 */
const getStatusType = (status: string) => {
    switch (status) {
        case 'published': return 'success'
        case 'draft': return 'warning'
        case 'archived': return 'info'
        default: return 'info'
    }
}

/**
 * 获取状态对应的显示文本
 * @param status - 文章状态
 * @returns 显示文本
 */
const getStatusText = (status: string) => {
    switch (status) {
        case 'published': return '已发布'
        case 'draft': return '草稿'
        case 'archived': return '已归档'
        default: return status
    }
}

/**
 * 格式化日期显示
 * @param dateString - ISO格式的日期字符串
 * @returns 格式化后的本地日期字符串
 */
const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
}

// 组件挂载时获取初始数据
onMounted(async () => {
    try {
        await Promise.all([
            fetchPosts(),
            fetchCategories()
        ])
    } catch (error) {
        console.error('初始化数据失败:', error)
        useSampleData()
    }
})
</script>

<style scoped lang="scss">
// 导入文章列表管理页面样式
@use '../../assets/styles/admin/_posts';
</style>